package com.helper.easyHelper.utils;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.CaseFormat;
import com.helper.easyHelper.common.entity.Column;
import com.helper.easyHelper.common.entity.Table;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 狠穿
 * @version 1.0.0
 * @date 2023/1/29
 * @function mysql工具类
 */
public class MySQLUtils {

    /**
     * 获取表信息
     * @param name
     * @return
     */
    public static Table getTableInfo(String name){
        Table table = new Table();
        table.setName(name);
        //处理表
        table.setModelName(PCUtils.getBaseName(table.getName())+"PO");
        table.setMapperName(PCUtils.getBaseName(table.getName())+"Mapper");
        table.setManagerName(PCUtils.getBaseName(table.getName())+"Manager");
        table.setManagerImplName(table.getManagerName()+"Impl");

        //处理字段
        String sql = "SHOW FULL COLUMNS FROM {}";
        sql = StrUtil.format(sql,name);
        Connection conn = DBUtils.getConnection();
        try {
            Statement sta  = conn.createStatement();
            ResultSet resultSet = sta.executeQuery(sql);
            List<Column> columns = new ArrayList<>();
            while(resultSet.next()){
                String columnName = resultSet.getString("Field");
                String columnType = resultSet.getString("Type");
                String javaType = Column.fromType(columnType);
                String nullStr = resultSet.getString("Null");
                String keyStr = resultSet.getString("Key");
                String defaultValue = resultSet.getString("Default");
                String comment = resultSet.getString("Comment");
                Column column = new Column();
                column.setDbName(columnName);
                column.setJavaName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName));
                column.setDbType(columnType);
                column.setJavaType(javaType);
                column.setDefaultValue(defaultValue);
                column.setComment(comment);
                if(StrUtil.equalsIgnoreCase(nullStr,"NO")){
                    column.setNullable(false);
                }
                if(StrUtil.equalsIgnoreCase(keyStr,"PRI")){
                    column.setPrimaryKey(true);
                }
                columns.add(column);
            }
            table.setColumns(columns);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return table;
    }

}
